const db = require('../db/db');

// 创建名片夹
exports.createFolder = async (req, res) => {
  try {
    const { name, description } = req.body;
    const userId = req.user.id;

    const result = await db.query(
      'INSERT INTO card_folders (user_id, name, description) VALUES (?, ?, ?)',
      [userId, name, description]
    );

    res.json({
      success: true,
      folderId: result.insertId
    });
  } catch (error) {
    console.error('创建名片夹错误:', error);
    res.status(500).json({
      success: false,
      message: '创建名片夹失败'
    });
  }
};

// 获取用户的名片夹列表
exports.getFolders = async (req, res) => {
  try {
    const userId = req.user.id;
    const folders = await db.query(
      'SELECT id, name, description FROM card_folders WHERE user_id = ?',
      [userId]
    );

    res.json({
      success: true,
      folders
    });
  } catch (error) {
    console.error('获取名片夹错误:', error);
    res.status(500).json({
      success: false,
      message: '获取名片夹失败'
    });
  }
};

// 更新名片夹
exports.updateFolder = async (req, res) => {
  try {
    const { name, description } = req.body;
    const { id } = req.params;
    const userId = req.user.id;

    // 验证名片夹属于当前用户
    const folderRows = await db.query(
      'SELECT id FROM card_folders WHERE id = ? AND user_id = ?',
      [id, userId]
    );
    
    if (!folderRows || folderRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片夹不存在'
      });
    }

    await db.query(
      'UPDATE card_folders SET name = ?, description = ? WHERE id = ?',
      [name, description, id]
    );

    res.json({
      success: true,
      message: '名片夹更新成功'
    });
  } catch (error) {
    console.error('更新名片夹错误:', error);
    res.status(500).json({
      success: false,
      message: '更新名片夹失败'
    });
  }
};

// 删除名片夹
exports.deleteFolder = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 验证名片夹属于当前用户
    const folderRows = await db.query(
      'SELECT id FROM card_folders WHERE id = ? AND user_id = ?',
      [id, userId]
    );
    
    if (!folderRows || folderRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片夹不存在'
      });
    }

    await db.query('DELETE FROM card_folders WHERE id = ?', [id]);

    res.json({
      success: true,
      message: '名片夹删除成功'
    });
  } catch (error) {
    console.error('删除名片夹错误:', error);
    res.status(500).json({
      success: false,
      message: '删除名片夹失败'
    });
  }
};

// 创建名片
exports.createCard = async (req, res) => {
  try {
    const { folderId } = req.params;
    const {
      name, title, department, company,
      phone, email, address, zip, notes
    } = req.body;
    const userId = req.user.id;

    // 基本验证
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '姓名不能为空'
      });
    }

    // 验证邮编长度
    if (zip && zip.length > 20) {
      return res.status(400).json({
        success: false,
        message: '邮编长度不能超过20个字符'
      });
    }

    // 验证名片夹属于当前用户
    const folderRows = await db.query(
      'SELECT id FROM card_folders WHERE id = ? AND user_id = ?',
      [folderId, userId]
    );
    
    if (!folderRows || folderRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片夹不存在'
      });
    }

    // 处理可能为null的值，避免数据库错误
    const cleanedZip = zip || '';
    const cleanedTitle = title || '';
    const cleanedDepartment = department || '';
    const cleanedCompany = company || '';
    const cleanedPhone = phone || '';
    const cleanedEmail = email || '';
    const cleanedAddress = address || '';
    const cleanedNotes = notes || '';

    const result = await db.query(
      `INSERT INTO business_cards 
      (user_id, folder_id, name, title, department, company, phone, email, address, zip, notes) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [userId, folderId, name, cleanedTitle, cleanedDepartment, cleanedCompany, 
       cleanedPhone, cleanedEmail, cleanedAddress, cleanedZip, cleanedNotes]
    );

    res.json({
      success: true,
      cardId: result.insertId
    });
  } catch (error) {
    console.error('创建名片错误:', error);
    // 提供更详细的错误信息
    res.status(500).json({
      success: false,
      message: '创建名片失败',
      error: error.message
    });
  }
};

// 获取名片夹中的名片列表
exports.getCards = async (req, res) => {
  try {
    const { folderId } = req.params;
    const userId = req.user.id;

    // 验证名片夹属于当前用户
    const folderRows = await db.query(
      'SELECT id FROM card_folders WHERE id = ? AND user_id = ?',
      [folderId, userId]
    );
    
    if (!folderRows || folderRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片夹不存在'
      });
    }

    const cards = await db.query(
      `SELECT id, name, title, department, company, phone, email 
       FROM business_cards 
       WHERE folder_id = ? AND user_id = ?`,
      [folderId, userId]
    );

    res.json({
      success: true,
      cards
    });
  } catch (error) {
    console.error('获取名片错误:', error);
    res.status(500).json({
      success: false,
      message: '获取名片失败'
    });
  }
};

// 获取单个名片详情
exports.getCard = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const cardRows = await db.query(
      `SELECT * FROM business_cards 
       WHERE id = ? AND user_id = ?`,
      [id, userId]
    );
    
    if (!cardRows || cardRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片不存在'
      });
    }

    res.json({
      success: true,
      card: cardRows[0]
    });
  } catch (error) {
    console.error('获取名片详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取名片详情失败'
    });
  }
};

// 更新名片
exports.updateCard = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    const {
      name, title, department, company,
      phone, email, address, zip, notes
    } = req.body;

    // 验证名片属于当前用户
    const cardRows = await db.query(
      'SELECT id FROM business_cards WHERE id = ? AND user_id = ?',
      [id, userId]
    );
    
    if (!cardRows || cardRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片不存在'
      });
    }

    await db.query(
      `UPDATE business_cards 
       SET name = ?, title = ?, department = ?, company = ?, 
           phone = ?, email = ?, address = ?, zip = ?, notes = ? 
       WHERE id = ?`,
      [name, title, department, company, phone, email, address, zip, notes, id]
    );

    res.json({
      success: true,
      message: '名片更新成功'
    });
  } catch (error) {
    console.error('更新名片错误:', error);
    res.status(500).json({
      success: false,
      message: '更新名片失败'
    });
  }
};

// 删除名片
exports.deleteCard = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 验证名片属于当前用户
    const cardRows = await db.query(
      'SELECT id FROM business_cards WHERE id = ? AND user_id = ?',
      [id, userId]
    );
    
    if (!cardRows || cardRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '名片不存在'
      });
    }

    await db.query('DELETE FROM business_cards WHERE id = ?', [id]);

    res.json({
      success: true,
      message: '名片删除成功'
    });
  } catch (error) {
    console.error('删除名片错误:', error);
    res.status(500).json({
      success: false,
      message: '删除名片失败'
    });
  }
};

// 获取名片夹详情列表（包含名片数量和最后更新时间）
exports.getFoldersWithDetails = async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户所有的名片夹
    const folders = await db.query(
      'SELECT id, name, description, created_at, updated_at FROM card_folders WHERE user_id = ?',
      [userId]
    );
    
    // 为每个名片夹获取详细信息
    const foldersWithDetails = await Promise.all(
      folders.map(async (folder) => {
        // 获取该名片夹中的名片数量
        const countResult = await db.query(
          'SELECT COUNT(*) as count FROM business_cards WHERE folder_id = ? AND user_id = ?',
          [folder.id, userId]
        );
        
        const cardCount = countResult[0].count;
        
        // 获取该名片夹中最近更新的名片
        const latestCards = await db.query(
          'SELECT updated_at FROM business_cards WHERE folder_id = ? AND user_id = ? ORDER BY updated_at DESC LIMIT 1',
          [folder.id, userId]
        );
        
        let lastUpdated = folder.updated_at;
        if (latestCards && latestCards.length > 0 && latestCards[0].updated_at) {
          // 如果名片夹中有名片，并且最新名片的更新时间晚于名片夹的更新时间，使用名片的更新时间
          const cardUpdateTime = new Date(latestCards[0].updated_at);
          const folderUpdateTime = new Date(folder.updated_at);
          
          if (cardUpdateTime > folderUpdateTime) {
            lastUpdated = latestCards[0].updated_at;
          }
        }
        
        return {
          ...folder,
          cardCount,
          lastUpdated
        };
      })
    );
    
    res.json({
      success: true,
      folders: foldersWithDetails
    });
  } catch (error) {
    console.error('获取名片夹详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取名片夹详情失败'
    });
  }
};

// 批量录入名片
exports.batchCreateCards = async (req, res) => {
  try {
    const { data } = req.body;
    const userId = req.user.id;
    
    if (!Array.isArray(data) || data.length === 0) {
      return res.status(400).json({
        success: false,
        message: '无效的数据格式，需要提供名片数组'
      });
    }

    // 获取用户的所有名片夹
    const userFolders = await db.query(
      'SELECT id, name FROM card_folders WHERE user_id = ?',
      [userId]
    );

    if (!userFolders || userFolders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户没有名片夹，请先创建名片夹'
      });
    }

    // 创建名片夹名称到ID的映射
    const folderNameToIdMap = {};
    userFolders.forEach(folder => {
      folderNameToIdMap[folder.name] = folder.id;
    });

    // 设置默认名片夹
    const defaultFolderId = userFolders[0].id;

    // 数据验证结果
    const validationResults = {
      success: [],
      failed: []
    };

    // 开始事务
    await db.beginTransaction();
    
    try {
      // 批量插入处理
      for (const card of data) {
        try {
          // 基本验证
          if (!card.name) {
            validationResults.failed.push({
              card,
              reason: '姓名不能为空'
            });
            continue;
          }

          // 验证邮编长度
          if (card.zip && card.zip.length > 20) {
            validationResults.failed.push({
              card,
              reason: '邮编长度不能超过20个字符'
            });
            continue;
          }

          // 处理字段值，确保它们不为undefined，并去除前后空格
          const cleanedCard = {
            name: (card.name || '').trim(),
            title: (card.title || '').trim(),
            department: (card.department || '').trim(),
            company: (card.company || '').trim(),
            phone: (card.phone || '').trim(),
            email: (card.email || '').trim(),
            address: (card.address || '').trim(),
            zip: (card.zip || '').trim(),
            notes: (card.notes || '').trim(),
            folder: (card.folder || '').trim()
          };

          let folderId;
          // 如果指定了名片夹
          if (cleanedCard.folder) {
            // 尝试通过名片夹名称查找ID
            if (folderNameToIdMap[cleanedCard.folder]) {
              folderId = folderNameToIdMap[cleanedCard.folder];
            } else {
              // 如果名片夹不存在，则创建一个新的名片夹
              const folderResult = await db.query(
                'INSERT INTO card_folders (user_id, name, description) VALUES (?, ?, ?)',
                [userId, cleanedCard.folder, `自动创建的名片夹: ${cleanedCard.folder}`]
              );
              folderId = folderResult.insertId;
              // 添加到映射中以供后续使用
              folderNameToIdMap[cleanedCard.folder] = folderId;
            }
          } else {
            // 如果没有指定名片夹，使用默认名片夹
            folderId = defaultFolderId;
          }

          // 插入数据库
          const result = await db.query(
            `INSERT INTO business_cards 
            (user_id, folder_id, name, title, department, company, phone, email, address, zip, notes) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
              userId, 
              folderId, 
              cleanedCard.name, 
              cleanedCard.title, 
              cleanedCard.department, 
              cleanedCard.company, 
              cleanedCard.phone, 
              cleanedCard.email, 
              cleanedCard.address, 
              cleanedCard.zip, 
              cleanedCard.notes
            ]
          );

          // 添加到成功列表
          validationResults.success.push({
            id: result.insertId,
            name: cleanedCard.name,
            folder: cleanedCard.folder || userFolders.find(f => f.id === defaultFolderId)?.name || '默认'
          });
        } catch (error) {
          console.error('批量添加名片错误:', error);
          validationResults.failed.push({
            card,
            reason: error.message
          });
        }
      }

      // 提交事务
      await db.commit();
      
      // 返回结果
      return res.json({
        success: true,
        count: validationResults.success.length,
        failed: validationResults.failed.length,
        details: {
          success: validationResults.success,
          failed: validationResults.failed
        }
      });
    } catch (error) {
      // 回滚事务
      await db.rollback();
      throw error;
    }
  } catch (error) {
    console.error('批量添加名片错误:', error);
    res.status(500).json({
      success: false,
      message: '批量添加名片失败',
      error: error.message
    });
  }
};
